package com.opennetexam.manager.bussinessservice;

import com.openexam.openqti.openqtipaperquestion.*;
import com.openexam.openqti.qti.AssessmentItem;
import com.openexam.openqti.qti.AssessmentTest;
import com.opennetexam.manager.common.*;
import com.opennetexam.manager.mapper.*;
import com.opennetexam.manager.databasemodel.*;
import com.opennetexam.manager.dto.*;
import com.opennetexam.manager.enums.*;
import com.opennetexam.manager.itemmodel.ICreaterFactory;
import com.opennetexam.manager.readxml.LoadXml;
import com.opennetexam.manager.utils.*;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import java.io.File;
import java.util.*;

/**
 * @author 奶茶
 * Created on 2017/11/14.
 */
@Service("examPaperService")
@Transactional(rollbackFor = Exception.class)
public class ExamPaperService {

    private static final Logger logger = Logger.getLogger(ExamPaperService.class);

    @Autowired
    private ExamineeArrangeMapper examineeArrangeMapper;
    @Autowired
    private ExamSubjectMapper examSubjectMapper;
    @Autowired
    private ExamScenesMapper examScenesMapper;
    @Autowired
    private ExamPaperMapper examPaperMapper;
    @Autowired
    private ExamineeExamPaperMapper examineeExamPaperMapper;
    @Autowired
    private ExamineeExamPaperItemMapper examineeExamPaperItemMapper;
    @Autowired
    private ExamPlanInfoMapper examPlanInfoMapper;
    @Autowired
    private ExamMoniterMapper examMoniterMapper;
    @Autowired
    private BeforeExamService beforeExamService;
    @Autowired
    private ExamPaperItemMapper examPaperItemMapper;

    private static JAXBContext assessmentTestJAXBContext;
    private static JAXBContext assessmentItemJAXBContext;
    static {
        try {
            assessmentTestJAXBContext = JAXBContext.newInstance(AssessmentTest.class);
            assessmentItemJAXBContext = JAXBContext.newInstance(AssessmentItem.class);
        } catch (JAXBException e) {
            logger.error("JAXBException",e);
        }
    }

    private static final String FORMATPATH = "%s/%s/%s/%s/";
    private static final String PAPERFOLDER = "/files/papers";



    /**
     * 根据考试计划获取科目列表
     * @param planId
     * @param appId
     * @return
     */
    public List<ExamPaperCount> getExamSubject(String planId, String appId){
        List<ExamPaperCount> examPaperCountList = new ArrayList<>();
        //获取考试计划信息,匹配考试计划和编排表
        List<ArrangesInfo> arranges = examineeArrangeMapper.findArranges(planId, appId);
        if(!arranges.isEmpty()){
            for (ArrangesInfo arrangesInfo:arranges) {
                Integer count = examineeExamPaperMapper.getExamineeExamPaperCountBySomeWhere(arrangesInfo.getAppId(), arrangesInfo.getExamPlanInfoId(), arrangesInfo.getExamSubjectID());
                ExamSubject examSubject = examSubjectMapper.examSubjectFirstOrDefault(arrangesInfo.getAppId(), arrangesInfo.getExamPlanInfoId(), arrangesInfo.getExamSubjectID());
                ExamScenes examScenes = examScenesMapper.examScenedFirstOrDefault(arrangesInfo.getExamSceneID());
                ExamPaperCount examPaperCount = new ExamPaperCount();
                examPaperCount.setNeedCount(arrangesInfo.getCount());
                examPaperCount.setNowCount(count);
                examPaperCount.setExamSubjectId(arrangesInfo.getExamSubjectID());
                examPaperCount.setExamSubjectName(examSubject.getSubjectName());
                examPaperCount.setExamSceneId(examScenes.getExamSceneID());
                examPaperCount.setExamSceneName(examScenes.getExamSceneName());
                examPaperCount.setExamScenePlanBeginTime(examScenes.getPlanBeginTime());

                examPaperCountList.add(examPaperCount);
            }
        }

        return examPaperCountList;
    }

    /**
     * 生成试卷前判断
     * @param planId
     * @param subjectId
     * @param adminInfo
     * @return
     */
    public OperationResult paperGenerat(String planId, String subjectId, AdminInfo adminInfo) throws Exception {
        OperationResult result = isSeatSet(planId, adminInfo.getAppID());
        if(result.getResultType() != OperationResultType.Success){
            return new OperationResult(OperationResultType.Error,"当前座位号没设置完全，需要设置");
        }

        Integer counts = paperGenerats(planId, subjectId, adminInfo);
        return new OperationResult(OperationResultType.Success,counts);
    }

    /**
     * 当前计划的座位号是否需要限制，以及是否已生成座位号
     * @param planId
     * @param appId
     * @return
     */
    public OperationResult isSeatSet(String planId, String appId){
        List<ExamPlanInfo> examPlanInfos = examineeArrangeMapper.findExamPlanInfoBySomeWhere(planId, appId);
        if(!examPlanInfos.isEmpty()){
            return new OperationResult(OperationResultType.Success);
        }
        List<ArrangesInfo> arrangesInfos = examineeArrangeMapper.ExamineeArrangesWhere(planId, appId);
        List<ExamComputer> examComputers = examineeArrangeMapper.findExamComputerBySomeWhere(appId, planId);

        return arrangesInfos.size() <= examComputers.size()
                ? new OperationResult(OperationResultType.Success)
                : new OperationResult(OperationResultType.Warning,"当前座位号没设置完全，需要设置！");
    }

    /**
     * 生成试卷
     * @param planId 考试计划ID
     * @param subjectId 科目ID
     * @param adminInfo 主办方
     * @return
     */
    public Integer paperGenerats(String planId, String subjectId, AdminInfo adminInfo) throws Exception {
        Integer paperCount = 0;
        String appId = adminInfo.getAppID();
        Integer deploymentMode = examPlanInfoMapper.getDeploymentMode(appId, planId);
        //获取未生成试卷的考生编排信息
        List<ExamineeArrange> examineeArranges = examineeArrangeInfo(planId, subjectId, appId);
        //试卷是否乱序
        //Short paperShuffled = examSubjectMapper.examPaperIsShuffled(subjectId).getPaperShuffled();
        //boolean isShuffle = paperShuffled.equals(SystemBoolean.False.getPrefix().shortValue()) ? false : true;
        boolean isShuffle = false;

        for (ExamineeArrange examineeArrange:examineeArranges) {
            paperCount++;
            ExamPaper examPaper = examPaperInfo(planId, subjectId, appId);
            List<ExamPaperItem> examPaperItems = examPaperItemInfo(examPaper.getPaperID());
            //Map<String,String> dic = new HashMap<>();
            //for (ExamPaperItem examPaperItem:examPaperItems) {
            //    dic.put(examPaperItem.getItemID(),examPaperItem.getItemContent());
            //}

            TestPaperOutModel testPaperOutModel = new TestPaperOutModel();
            testPaperOutModel.setTestString(examPaper.getExamPaperContent());
            //testPaperOutModel.setQuestionDic(dic);

            //乱序试卷
            TestPaperOutModel outModel = new TestPaperFromPackageGenerator().generator(testPaperOutModel, isShuffle,assessmentTestJAXBContext,assessmentItemJAXBContext);

            //填充考生考试试卷表
            ExamineeExamPaper examineeExamPaper = new ExamineeExamPaper();
            examineeExamPaper.setExamPaperInfoID(UUID.randomUUID().toString());
            examineeExamPaper.setExamineeID(examineeArrange.getExamineeID());
            examineeExamPaper.setExamineeReport("");
            examineeExamPaper.setExamPaperID(examPaper.getExamPaperID());
            examineeExamPaper.setExamPaperContent(outModel.getTestString());
            examineeExamPaper.setAppID(examineeArrange.getAppID());
            examineeExamPaper.setExamPlanInfoID(examineeArrange.getExamPlanInfoID());
            examineeExamPaper.setPaperVersion(examPaper.getPaperVersion());
            examineeExamPaper.setExamSceneID(examineeArrange.getExamSceneID());
            examineeExamPaper.setExamSubjectID(examineeArrange.getExamSubjectID());
            examineeExamPaper.setSysState(SystemBoolean.True.getPrefix().shortValue());
            examineeExamPaper.setCreateTime(DateUtil.convertEncryptDateToString(new Date()));

            List<ExamineeExamPaperItem> paperItemList = new ArrayList<>();
            String paperID = examPaper.getPaperID();
            String examPaperInfoID = examineeExamPaper.getExamPaperInfoID();
            for (ExamPaperItem examPaperItem:examPaperItems) {
                ExamineeExamPaperItem paperItem = new ExamineeExamPaperItem();
                paperItem.setItemID(examPaperItem.getItemID());
                paperItem.setItemContent(examPaperItem.getItemContent());
                paperItem.setPaperID(paperID);
                paperItem.setExamPaperInfoID(examPaperInfoID);
                paperItemList.add(paperItem);
            }
            buildJsonPaper(examineeExamPaper,paperItemList,deploymentMode);
        }

        if(state(planId,appId)){
            ExamPlanInfo examPlanInfo = examPlanInfoMapper.getExamPlanInfoBySysState(appId, planId,ExamPlanSysState.Downloading.getPrefix());
            examPlanInfo.setSysState(ExamPlanSysState.TestPaperCreated.getPrefix());
            examPlanInfoMapper.updateExamPalnSyState(examPlanInfo);
        }

        return paperCount;
    }

    /**
     * 获取未生成试卷的考生编排信息
     * @param planId
     * @param subjectId
     * @param appId
     * @return
     */
    public List<ExamineeArrange> examineeArrangeInfo(String planId, String subjectId, String appId){
        //基础参数检查
        PublicHelper.checkArgument(planId,"examPlanInfoId");
        PublicHelper.checkArgument(subjectId,"examSubjectId");
        PublicHelper.checkArgument(appId,"appID");

        //获取符合条件的学生编排信息数据
        List<ExamineeArrange> examineeArranges = examineeArrangeMapper.examineeArrangeWhere(appId, planId, subjectId);
        if(examineeArranges.isEmpty()){
            return examineeArranges;
        }else{
            //获取未生成试卷的考生编排
            return examineeArrangeMapper.examineeNotArrangeWhere(appId, planId, subjectId);
        }
    }

    /**
     * 根据考试计划，科目获取课程原始试卷信息
     * @param planId
     * @param subjectId
     * @param appId
     * @return
     */
    public ExamPaper examPaperInfo(String planId, String subjectId, String appId){
        //基础参数检查
        PublicHelper.checkArgument(planId, "examPlanInfoID");
        PublicHelper.checkArgument(subjectId, "examSubjectId");
        PublicHelper.checkArgument(appId, "appId");

        List<ExamPaper> examPapers = examPaperMapper.getExamPapersBySomeWhere(appId, planId, subjectId);
        int count = new Random().nextInt(examPapers.size());
        return examPapers.get(count);
    }

    /**
     * 根据试卷获取科目原始试题信息
     * @param paperId
     * @return
     */
    public List<ExamPaperItem> examPaperItemInfo(String paperId){
        // 基础参数检查
        PublicHelper.checkArgument(paperId, "paperId");
        return examPaperMapper.findExamPaperItemsByPaperId(paperId);
    }

    /**
     * 生成Json试卷
     * @param examPaper
     * @param examPaperItems
     */
    public void buildJsonPaper(ExamineeExamPaper examPaper,List<ExamineeExamPaperItem> examPaperItems,Integer deploymentMode) throws Exception {
        TestPaperTemplate testPaper = new TestPaperTemplate();
        OpenAssessmentTest openAssessmentTest = new OpenAssessmentTest();
        openAssessmentTest.LoadFromString(examPaper.getExamPaperContent(),assessmentTestJAXBContext);

        Integer itemCount = 0;
        Double score = 0.0;
        Integer i = 0;

        for (OpenTestPart testPart:openAssessmentTest.getTestPartCollection()) {
            for (OpenAssessmentSection section:testPart.getAssessmentSectionCollection()) {
                score += section.getScore();
                itemCount += section.getItemCount();

                SectionTemplate sectionTemplate = new SectionTemplate();
                sectionTemplate.setScore(section.getScore());
                sectionTemplate.setIdentifier(section.getIdentifier());
                sectionTemplate.setItemCount(section.getItemCount());
                sectionTemplate.setTitle(section.getTitle());
                sectionTemplate.setItemIndex(testPaper.getSectionTemplateCollection().size() + 1);

                for (OpenAssessmentItemRef itemRef:section.getAssessmentItemRefCollection()) {
                    OpenAssessmentItem item = OpenAssessmentItem.createInstance(itemRef.getType());
                    ExamineeExamPaperItem paperItem = CommonFunction.getExamPaperItemById(examPaperItems, itemRef.getIdentifier());
                    if(paperItem == null){
                        System.out.println(examPaper);
                    }
                    item.LoadFromString(CommonFunction.getExamPaperItemById(examPaperItems,itemRef.getIdentifier()).getItemContent(),assessmentItemJAXBContext);

                    ItemTemplate temp = ICreaterFactory.getItemObject(item);
                    temp.setAssessmentItemType(itemRef.getType().getIndex());
                    temp.setIdentifier(itemRef.getIdentifier());
                    temp.setExample(itemRef.isExample());
                    temp.setMedia(itemRef.getMedia());
                    temp.setSubjective(itemRef.isSubjective());
                    temp.setTitle(item.getTitle());
                    temp.setWeight(itemRef.getWeight());
                    temp.setResponseDuration(itemRef.getResponseDuration());
                    temp.setQuestionAnalysis("");
                    temp.setPromptShowDuration(itemRef.getPromptShowDuration());
                    temp.setScore(itemRef.getWeight());
                    temp.setItemIndex(sectionTemplate.getItemTemplateCollection().size()+1);
                    temp.setSequenceIndex(++i);
                    sectionTemplate.getItemTemplateCollection().add(temp);
                }
                testPaper.getSectionTemplateCollection().add(sectionTemplate);
            }
        }

        testPaper.setIdentifier(examPaper.getExamPaperInfoID());
        testPaper.setTitle(openAssessmentTest.getTitle());
        testPaper.setItemCount(itemCount);
        testPaper.setScore(score);

        String paperStr = GsonUtil.toJson(testPaper);
        examPaper.setExamPaperContent(paperStr);

        if(deploymentMode.equals(DeploymentMode.LAN_Deployment.getPrefix())){
            String path = String.format(FORMATPATH,ExamSitePath.rootPath + PAPERFOLDER,examPaper.getAppID(),examPaper.getExamPlanInfoID(),examPaper.getExamSubjectID());
            String filePath = String.format("%s.json",examPaper.getExamPaperInfoID());

            FileUtil.writeStrToFile(path,filePath,paperStr);
        }else {
            //将试卷放入缓存
            String examinerCacheKey = CacheKey.getExaminerPaperKey(examPaper.getExamPlanInfoID(),examPaper.getExamSubjectID(),examPaper.getExamSceneID(),examPaper.getExamineeID());
            //从缓存中获取计划的周期时长
            String examPlanID = examPaper.getExamPlanInfoID();
            String examPlanTime = RedisUtil.getValue(examPlanID);
            if(!StringUtils.isEmpty(examPlanTime)){
                RedisUtil.setValue(examinerCacheKey,paperStr,Integer.valueOf(examPlanTime));
            }else{
                //计算计划的周期时长  场次结束时间和当前时间的差值 作为考生试卷的缓存的过期时间
                ExamScenes examScene = examScenesMapper.getExamSceneByExamPlanID(examPlanID);
                String endTime = examScene.getPlanEndTime();
                Long time = (DateUtil.convertStringToDate(endTime).getTime() - System.currentTimeMillis())/1000;
                RedisUtil.setValue(examPaper.getExamPlanInfoID(),time.toString(),time.intValue());
                RedisUtil.setValue(examinerCacheKey,paperStr,time.intValue());
            }
        }
        saveExamineeExam(examPaper);
    }

    /**
     * 保存考生试卷和试题
     * @param paper
     * @return
     */
    public void saveExamineeExam(ExamineeExamPaper paper){
        // 基础参数检查
        PublicHelper.checkArgument(paper, "exanineeExamPaper");
        examineeExamPaperMapper.insertExamineeExamPaper(paper);
    }

    /**
     * 检查是否允许清理已生成的试卷
     * @param appId 主办方id
     * @param planId 计划id
     * @param subjectId 科目id
     * @return
     */
    public OperationResult checkBeforeClean(String appId, String planId, String subjectId){
        ExamPlanInfo examPlanInfo = examPlanInfoMapper.getExamPlanInfoBySysState(appId, planId,ExamPlanSysState.TestPaperCreated.getPrefix());

        if(examPlanInfo == null){
            return new OperationResult(OperationResultType.Warning,"指定的考试计划信息不存在！");
        }

        //判断所有类型的考试  不仅仅是统考和预考
        List<ExamingMonitor> examingMonitorList = examMoniterMapper.findExamingMoniterWhereLogin(appId, planId, subjectId, ExamManagerState.Discipline.getPrefix());
        Integer examStartCount = 0;
        if(examingMonitorList != null && !examingMonitorList.isEmpty()){
            examStartCount = examingMonitorList.size();
        }

        return examStartCount > 0
                ? new OperationResult(OperationResultType.Warning,"当前有正在考试的学生，不能进行清理试卷！")
                : new OperationResult(OperationResultType.Success,"检查成功，可以清理试卷！");
    }

    /**
     * 清理已生成的考试试卷
     * @param appId
     * @param planId 考试计划ID
     * @param subjectId 考试科目ID
     * @return
     */
    public OperationResult cleanPaper(String appId, String planId, String subjectId){
        //找到数据库中的指定该科试卷
        List<ExamineeExamPaper> examineeExamPapers = examineeExamPaperMapper.findExamineePaperByAppIdAndPlanIdAndSubjectId(appId, planId, subjectId);
        //删除数据库已生成的考试试卷相关的数据
        for (ExamineeExamPaper examPaper:examineeExamPapers) {
            List<ExamineeExamPaperItem> examineeExamPaperItems = examineeExamPaperItemMapper.findExamineePaperItemByExamPaperInfoId(examPaper.getExamPaperInfoID());
            //删除paperItems
            if(examineeExamPaperItems != null && !examineeExamPaperItems.isEmpty()){
                examineeExamPaperItemMapper.deleteExamineeExamPaperItems(examineeExamPaperItems);
            }
            //删除生成的json试卷
            String path = String.format(FORMATPATH,ExamSitePath.rootPath + PAPERFOLDER,examPaper.getAppID(),examPaper.getExamPlanInfoID(),examPaper.getExamSubjectID());
            String filePath = String.format("%s.json",examPaper.getExamPaperInfoID());
            FileUtil.deleteFile(path+filePath);
        }
        if(!examineeExamPapers.isEmpty()){
            examineeExamPaperMapper.deleteExamineeExamPaper(examineeExamPapers);
        }

        //清理后将plan的状态改为已导入
        ExamPlanInfo examPlanInfo = examPlanInfoMapper.getExamPlanInfo(appId, planId);
        if(examPlanInfo == null){
            return new OperationResult(OperationResultType.Warning,"当前考试计划不存在！");
        }
        examPlanInfo.setSysState(ExamPlanSysState.Imported.getPrefix());

        examPlanInfoMapper.updateExamPalnSyState(examPlanInfo);

        return new OperationResult(OperationResultType.Success,"清理试卷成功！");
    }

    /**
     * 获取考试状态
     * @param appId
     * @param planId
     * @param subjectId
     * @return
     */
    public OperationResult getMoniterStatus(String appId, String planId, String subjectId){
        ExamPlanInfo examPlanInfo = examPlanInfoMapper.getExamPlanInfo(appId, planId);
        if(examPlanInfo == null){
            return new OperationResult(OperationResultType.Warning,"指定的考试计划信息不存在！");
        }

        //获取符合条件的监考数据
        List<ExamingMonitor> monitors = examMoniterMapper.findExamingMonitersByWhere(appId, planId, subjectId);
        Map<String, Object> countByStatus = CommonFunction.getCountByStatus(monitors);

        return new OperationResult(OperationResultType.Success,"获取成功！",countByStatus);
    }


    /**
     * 判断当前计划下试卷是否生成完成
     * @param planId
     * @param appId
     * @return
     */
    public Boolean state(String planId, String appId){
        Integer byPlanIdAndAppId = examineeArrangeMapper.getCountByPlanIdAndAppId(planId, appId);
        Integer countByPlanIdAndAppId = examineeExamPaperMapper.getCountByPlanIdAndAppId(planId, appId);
        return byPlanIdAndAppId.equals(countByPlanIdAndAppId);
    }

    /**
     * 下载试卷
     * @param token
     * @return
     */
    public TestPaperTemplate getStudentPaper(String token){
        //获取缓存数据
        ClientLoginModel clientLoginModel = beforeExamService.getEhCacheValue(token);
        ExamPlanInfo examPlan = clientLoginModel.getExamPlan();
        ExamSubject examSubject = clientLoginModel.getExamSubject();
        ExamineeArrange examArrange = clientLoginModel.getExamArrange();

        String examinerPaperKey = CacheKey.getPaperKey(examPlan.getExamPlanInfoID(),examSubject.getExamSubjectID(),examArrange.getExamPaperID());

        String pagerJson = RedisUtil.getValue(examinerPaperKey);
        if(StringUtils.isEmpty(pagerJson)){
            pagerJson = examPaperMapper.getExamPaperByID(examArrange.getExamPaperID());
        }
        return GsonUtil.fromJsonToObject(pagerJson, TestPaperTemplate.class);
    }

    /**
     * 下载科目试卷
     * @param adminInfo
     * @param examSubject
     * @param prefixPath
     * @param deploymentMode
     * @param examPlanID
     * @return
     */
    public void downLoadExamSubjectPaper(AdminInfo adminInfo, ExamSubject examSubject, StringBuilder prefixPath, Integer deploymentMode, String examPlanID){
        try {
            LoadXml loadXml = new LoadXml();
            List<ExamPaper> examPaperList = new ArrayList<>();
            List<ExamPaperItem> examPaperItemList = new ArrayList<>();
            String basePath = prefixPath.toString();
            String filePath = "";
            //获取该科目的试卷存放路径
            if(deploymentMode.equals(DeploymentMode.WAN_Deployment.getPrefix())){
                filePath = basePath + examSubject.getSubjectCode();
            }else{
                // TODO: 2018/9/17 机考模式 下载考试科目试卷 下载逻辑待实现
                // /data/server/examplan/{examplanid}/{examsiteid}/paper/{subjectcode}/ASsT_{paperid}.xml
            }

            File file = new File(filePath);
            if(file.exists() && file.isDirectory()){
                for (File paperFile:file.listFiles()) {
                    if(paperFile.isFile()){
                        String paperFilePath = paperFile.getAbsolutePath();
                        String paperID = paperFile.getName().split(".xml")[0];
                        String paperContent = FileUtil.getFileContent(paperFilePath);
                        ExamPaper examPaper = new ExamPaper();
                        examPaper.setAppID(adminInfo.getAppID());
                        examPaper.setPaperID(paperID);
                        examPaper.setExamPlanInfoID(examPlanID);
                        examPaper.setExamSubjectID(examSubject.getExamSubjectID());
                        examPaper.setExamPaperContent(paperContent);
                        examPaper.setPaperVersion(1);
                        examPaper.setExamPaperID(UUID.randomUUID().toString());
                        examPaperList.add(examPaper);

                        OpenAssessmentTest openAssessmentTest = loadXml.loadExamPaperXml(paperFilePath,assessmentTestJAXBContext);
                        List<OpenAssessmentItem> questionList = loadXml.getQuestionList(openAssessmentTest,filePath,assessmentItemJAXBContext);

                        for (OpenAssessmentItem openAssessmentItem:questionList) {
                            String xmlString = openAssessmentItem.getXmlString(assessmentItemJAXBContext);
                            //直接映射 不需要复制图片
                            ExamPaperItem examPaperItem = new ExamPaperItem();
                            examPaperItem.setPaperID(paperID);
                            examPaperItem.setItemContent(xmlString);
                            examPaperItem.setItemID(openAssessmentItem.getIdentifier());
                            examPaperItemList.add(examPaperItem);
                        }
                    }
                }
            }
            //机考模式 删除下载的压缩文件 待下载逻辑实现
            if(deploymentMode.equals(DeploymentMode.LAN_Deployment.getPrefix())){
                FileUtil.deleteFile("");
            }

            //插入当前科目试卷和试题
            insertExamPaper(examPaperList);
            insertExamPaperItemList(examPaperItemList);

            //生成当前科目下所有考生试卷
            OperationResult paperGenerateResult = paperGenerat(examPlanID, examSubject.getExamSubjectID(), adminInfo);
            if(paperGenerateResult.getResultType().equals(OperationResultType.Success)){
                //下载完成将该科目试卷状态修改为_2(DownloadCompleteAndPaperGenerate)
                examSubject.setSubjectPaperStatus(SubjectPaperStatus.DownloadCompleteAndPaperGenerate.getPrefix().shortValue());
            }
        }catch (Exception e){
            examSubject.setSubjectPaperStatus(SubjectPaperStatus.DownloadFail.getPrefix().shortValue());
            logger.error("科目试卷下载异常！examSubjectID:" + examSubject.getExamSubjectID(),e);
        }finally {
            examSubjectMapper.updateExamSubjectPaperStatus(examSubject);
        }
    }

    private void insertExamPaper(List<ExamPaper> examPaperList){
        //添加或修改ExamPaper
        for (ExamPaper examPaper:examPaperList) {
            //List<ExamPaper> paperList = examPaperMapper.finaExamPaperBySomeWhere(examPaper.getExamPlanInfoID(), examPaper.getExamSubjectID(), examPaper.getPaperID());
            //if(paperList.isEmpty()){
            //    examPaperMapper.insertExamPaper(examPaper);
            //}
            examPaperMapper.insertExamPaperIFNotExist(examPaper);
        }
    }

    private void insertExamPaperItemList(List<ExamPaperItem> examPaperItemList){
        //添加ExamPaperItem
        for (ExamPaperItem examPaperItem:examPaperItemList) {
            //Integer integer = examPaperItemMapper.findExamPaperItemByItemId(examPaperItem.getItemID(), examPaperItem.getPaperID());
            //if(integer.equals(0)){
            //    examPaperItemMapper.insertExamPaperItem(examPaperItem);
            //}
            examPaperItemMapper.insertExamPaperItemIFNotExist(examPaperItem);
        }
    }
}
